package person.crud.dao;

import java.sql.SQLException;
import javax.sql.DataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;

//class connect/disconnect to DB by using AOP in PersonDAO class
@Aspect
public class ConnectDAO
{
    @Autowired
    DataSource dataSource;

    @Before("execution(* person.crud.dao.PersonDAO.getAll(..) )"
	    + "||execution(* person.crud.dao.PersonDAO.getCombined(..) )"
	    + "||execution(* person.crud.dao.PersonDAO.update(..) )" +

	    "||execution(* person.crud.dao.PersonDAO.add(..) )")
    // init
    void connectAndClear(JoinPoint joinPoint) throws SQLException
    {
	// dependency injection connection
	((PersonDAO) joinPoint.getThis()).setConn(dataSource.getConnection());

    }

    @After("execution(* person.crud.dao.PersonDAO.getAll(..) )"
	    + "||execution(* person.crud.dao.PersonDAO.getCombined(..) )"
	    + "||execution(* person.crud.dao.PersonDAO.update(..) )" +

	    "||execution(* person.crud.dao.PersonDAO.add(..) )")
    void disconnect(JoinPoint joinPoint)
    {

	try
	{// safe close connection
	    if ((((PersonDAO) joinPoint.getThis()).getConn() != null)
		    || !((PersonDAO) joinPoint.getThis()).getConn().isClosed())
	    {

		((PersonDAO) joinPoint.getThis()).getConn().close();

	    }
	} catch (SQLException e)
	{
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

    }

    public void init() throws SQLException
    {
	try
	{
	    dataSource
		    .getConnection()
		    .prepareStatement(
			    "CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, FirstName VARCHAR(100), LastName VARCHAR(100), age INT, sex ENUM('M','F'));")
		    .executeUpdate();

	} catch (SQLException e)
	{
	    throw new RuntimeException(e);

	}

    }
}
